//
//  CXCrashMgr.swift
//  CXRobotServer
//
//  Created by ezreal on 2019/4/24.
//

import Foundation

func SignalExceptionHandler(signal:Int32) -> Void
{
    var strCrash = "signal:\(signal)\n"
    strCrash += "Stack:\n"
    for symbol in Thread.callStackSymbols {
        strCrash = strCrash.appending("\(symbol)\r\n")
    }
    saveCrash(exceptionInfo: strCrash)
    exit(signal)
}

func saveCrash(exceptionInfo:String){
    let formatter = DateFormatter()
    formatter.timeZone = TimeZone(identifier: "Asia/Shanghai")
    formatter.dateFormat = "YYYY-MM-dd-HH:mm:ss"
    let dateString = formatter.string(from: Date())
    let crashFilePath = "\(Bundle.main.bundlePath)/\(dateString).log"
    try? exceptionInfo.write(toFile: crashFilePath, atomically: true, encoding: String.Encoding.utf8)
}

class CXCrashMgr: NSObject {

    static let shared = CXCrashMgr()
    
    private func registerSignalHandler()
    {
        signal(SIGABRT, SignalExceptionHandler)
        signal(SIGSEGV, SignalExceptionHandler)
        signal(SIGBUS, SignalExceptionHandler)
        signal(SIGTRAP, SignalExceptionHandler)
        signal(SIGILL, SignalExceptionHandler)
    }
    
    public func registerCrash(){
        self.registerSignalHandler()
    }
    
    func unregisterSignalHandler()
    {
        signal(SIGINT, SIG_DFL)
        signal(SIGSEGV, SIG_DFL)
        signal(SIGTRAP, SIG_DFL)
        signal(SIGABRT, SIG_DFL)
        signal(SIGILL, SIG_DFL)
    }
}
